<template>
  <div class="project-management-container">
    <div class="header">
      <div class="form-item">
        <el-button size="small" type="primary" @click="openDialog">创建项目</el-button>
      </div>
      <div class="form-item">
        <el-button size="small" type="primary" @click="handleSearch">搜索</el-button>
      </div>
      <div class="form-item">
        <span>状态：</span>
        <el-select size="small" v-model="status" placeholder="请选择">
          <el-option :key="-1" label="所有" value=""></el-option>
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="form-item">
        <span>项目名：</span>
        <el-input size="small" v-model="projectName" placeholder="请输入内容"></el-input>
      </div>
    </div>

    <el-empty v-if="!projectDatas.length" description="数据为空"></el-empty>
    <div v-else class="project-cards">
      <el-card class="project-card" v-for="(project, index) in projectDatas" :key="index">
        <div class="project-header">
          <el-button 
            type="danger" 
            size="mini" 
            @click="deleteProject(project.id, index)"
            class="delete-button"
          >
            删除
          </el-button>
        </div>
        <div class="project-info">
          <p><strong>项目名称：</strong>{{ project.projectName }}</p>
          <p><strong>评估方法：</strong>{{ project.evaluationMethod }}</p>
          <p><strong>计算模型：</strong>{{ project.calculationModel }}</p>
          <p><strong>项目状态：</strong>{{ project.status }}</p>
        </div>
        <el-button 
          v-if="project.status === 'UN_EVALUATE'" 
          type="primary" 
          size="small"
          @click="beginEvaluation(index)"
        >
          评估
        </el-button>
        <!-- <span v-if="project.status === 'EVALUATE'">已评估</span> -->
        <el-button type="text" size="small" @click="toDetail(project.id)">详情</el-button>
      </el-card>

      <div class="block-pagination">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange" 
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 40]" 
          :page-size="10" 
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog :visible.sync="dialogVisible" title="创建新项目" width="50%">
      <el-form :model="form" label-width="120px" :rules="rules" ref="form" status-icon>
        <el-form-item label="项目名称" prop="projectName" required>
          <el-input v-model="form.projectName" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        
        <el-form-item label="评估方法" prop="evaluationMethod" required>
          <el-select v-model="form.evaluationMethod" placeholder="请选择评估方法">
            <el-option label="估算功能点法" value="method1"></el-option>
            <!-- <el-option label="方法二" value="method2"></el-option> -->
          </el-select>
        </el-form-item>
        
        <el-form-item label="计算模型" prop="calculationModel" required>
          <el-select v-model="form.calculationModel" placeholder="请选择计算模型">
            <el-option label="文心一言（推荐）" value="model1"></el-option>
            <el-option label="Chatgpt" value="model2"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="上传文件" prop="fileList">
          <el-upload
            :action="''"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :file-list="fileList"
            accept=".txt"
            :limit="1"
            :headers="uploadHeaders"
            :data="{ userId: userId }"
            :auto-upload="false"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { getProjects } from '@/api/project';
import router from '@/router';

export default {
  name: 'ProjectManagement',
  data() {
    return {
      dialogVisible: false,
      form: {
        projectName: '',
        evaluationMethod: '',
        calculationModel: '',
      },
      fileList: [],
      projectDatas: [],
      pageNum: 1,
      pageSize: 100,
      status: "",
      projectName: '',
      total: 0,
      type: this.$store.getters.type,
      userId: this.$store.getters.id,
      options: [
        { label: "未评估", value: "UN_EVALUATE" },
        { label: "已评估", value: "EVALUATED" }
      ],
      rules: {
        projectName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ],
        evaluationMethod: [
          { required: true, message: '请选择评估方法', trigger: 'change' }
        ],
        calculationModel: [
          { required: true, message: '请选择计算模型', trigger: 'change' }
        ],
      },
      uploadHeaders: {
        'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes',
        'userId': this.userId
      }
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    getList() {
      const { pageNum, pageSize, status, projectName, type, userId, id } = this;
      getProjects({
        pageNum,
        pageSize,
        status,
        projectName,
        type,
        userId,
        id,
      }).then(res => {
        this.projectDatas = res.data.items;
        this.total = res.data.total;
        console.log('Projects loaded:', this.projectDatas);
      }).catch(error => {
        console.error('Error fetching project data:', error);
        this.$message.error('获取项目列表失败');
      });
    },
    init() {
      this.pageNum = 1;
      this.pageSize = 10;
      this.getList();
    },
    handleSearch() {
      this.init();
    },
    toDetail(projectId) {
      this.$router.push({ name: 'ResultShow', params: { id: projectId } });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getList();
    },
    openDialog() {
      this.dialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    beforeUpload(file) {
      const isTxt = file.type === 'text/plain';
      if (!isTxt) {
        this.$message.error('上传文件只能是 TXT 格式!');
      }
      return isTxt;
    },
    handleFileChange(file, fileList) {
      this.fileList = fileList.slice(-1); // 只保留最新上传的文件
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid && this.fileList.length > 0) {
          const formData = new FormData();
          formData.append('file', this.fileList[0].raw);
          formData.append('projectName', this.form.projectName);
          formData.append('evaluationMethod', this.form.evaluationMethod);
          formData.append('calculationModel', this.form.calculationModel);
          formData.append('userId', this.userId);

          axios.post('http://localhost:8080/project', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes'
            }
          })
          .then(response => {
            console.log('Response data:', response.data);
            this.$message.success('项目已创建并提交到服务器');
            const newProject = {
              projectName: this.form.projectName,
              evaluationMethod: this.form.evaluationMethod,
              calculationModel: this.form.calculationModel,
              status: '未提交',
              id: response.data.id
            };
            
            this.projectDatas.push(newProject);
            this.getList(); // Refresh the list to get the correct ID
            this.closeDialog();
            this.resetForm();
          })
          .catch(error => {
            this.$message.error('提交项目失败');
            console.error('Error:', error);
          });
        } else {
          this.$message.error('请完整填写所有信息并上传文件');
        }
      });
    },
    resetForm() {
      this.form = {
        projectName: '',
        evaluationMethod: '',
        calculationModel: '',
      };
      this.fileList = [];
    },
    beginEvaluation(index) {
      const project = this.projectDatas[index];
      if (!project) {
        this.$message.error('项目不存在');
        return;
      }

      if (!project.id) {
        this.$message.error('项目ID无效');
        return;
      }

      axios.get(`http://localhost:8080/project/begin/${project.id}`, null, {
        headers: {
          'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes'
        }
      })
      .then(response => {
        if (response.data.code === 1) {
          project.status = '评估中...';
          this.pollProjectStatus(project.id, index);
        } else {
          this.$message.error('评估启动失败，服务器返回错误代码');
        }
      })
      .catch(error => {
        this.$message.error('评估启动失败');
        console.error('Error:', error);
      });
    },
    pollProjectStatus(projectId, index) {
      const poll = setInterval(() => {
        axios.get(`http://localhost:8080/project/status?id=${projectId}`, {
          headers: {
            'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes'
          }
        })
        .then(response => {
          if (response.data.data === 'EVALUATED') {
            clearInterval(poll);
            // 修改项目状态
            this.projectDatas[index].status = '评估完成';
          }
        })
        .catch(error => {
          console.error('Error polling project status:', error);
        });
      }, 5000);
    },
    deleteProject(projectId, index) {
      axios.delete(`http://localhost:8080/project/delete?id=${projectId}`, {
        headers: {
          'token': 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOjUsImlhdCI6MTczMjExMjc1NCwiZXhwIjoxNzMyMTE5OTU0fQ.NX6iSNiY924va0E8YSxYD6HeYovvU9Eyb66RJl_GYes'
        }
      })
      .then(response => {
        if (response.data.code === 1) {
          this.$message.success('项目已成功删除');
          this.projectDatas.splice(index, 1); // 从前端列表中移除项目
          this.total -= 1; // 更新项目总数
        } else {
          this.$message.error('删除项目失败，服务器返回错误代码');
        }
      })
      .catch(error => {
        this.$message.error('删除项目失败');
        console.error('Error:', error);
      });
    },
    goToNextStep() {
      this.$router.push({ name: 'ProjectConfirm' });
    }
  }
}
</script>

<style scoped>
.project-management-container {
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  .form-item {
    display: flex;
    align-items: center;
    font-size: 14px;
    margin-right: 10px;
    span {
      flex-shrink: 0;
      color: #333;
      font-weight: bold;
    }
  }
}

.project-cards {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
}

.project-card {
  width: 300px;
  border: 1px solid #ebebeb;
  padding: 15px;
  position: relative;
}

.project-header {
  position: absolute;
  top: 10px;
  right: 10px;
}

.project-info {
  margin-bottom: 10px;
}

.block-pagination {
  width: 100%;
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.delete-button {
  position: absolute;
  top: 10px;
  right: 10px;
}
</style>
